// 引入组件库的少量全局样式变量
import 'tdesign-vue-next/es/style/index.css';

import TDesign from 'tdesign-vue-next';
import { type QiankunProps, qiankunWindow, renderWithQiankun } from 'vite-plugin-qiankun/dist/helper';
import type { App as VueApp } from 'vue';
import { createApp } from 'vue';

import DashboardApp from './DashboardApp.vue';
import i18n from './locales';
import router from './router';
import pinia from './store';

// 声明qiankun全局变量
declare global {
  interface Window {
    __POWERED_BY_QIANKUN__?: boolean;
  }
}

let app: VueApp<Element> | null = null;

// 创建应用的函数
function createMicroApp(props: QiankunProps = {}) {
  console.log('[DashboardApp] 创建应用，props:', props);

  // 创建应用实例
  app = createApp(DashboardApp);

  // 配置应用
  app.use(pinia);
  app.use(router);
  app.use(TDesign);
  app.use(i18n);

  // 注入全局属性用于与其他微应用通信
  if (props?.getGlobalState) {
    app.config.globalProperties.$getGlobalState = props.getGlobalState;
  }

  if (props?.setGlobalState) {
    app.config.globalProperties.$setGlobalState = props.setGlobalState;
  }

  // 注入消息服务
  if (props?.messageService) {
    app.config.globalProperties.$messageService = props.messageService;
  }

  // 关键修复：确保容器正确获取和使用
  let container = null;

  // 1. 优先使用props中的容器
  if (props?.container) {
    if (typeof props.container === 'string') {
      container = document.querySelector(props.container);
      console.log(`[DashboardApp] Found container by selector "${props.container}":`, container);
    } else {
      container = props.container;
      console.log('[DashboardApp] Using provided DOM element container:', container);
    }
  }

  // 2. 如果没有找到容器，尝试默认选择器
  if (!container) {
    const selectors = ['#micro-container', '#dashboard-app-app', '#dashboard-app'];
    for (const selector of selectors) {
      container = document.querySelector(selector);
      if (container) {
        console.log(`[DashboardApp] Found fallback container "${selector}":`, container);
        break;
      }
    }
  }

  // 3. 最后的备选方案：使用body
  if (!container) {
    container = document.body;
    console.log('[DashboardApp] Using body as container:', container);
  }

  // 清空容器内容（防止重复挂载）
  if (container) {
    container.innerHTML = '';

    // 为微前端环境添加特殊的CSS类
    if (props?.container || window.__POWERED_BY_QIANKUN__) {
      container.classList.add('micro-frontend');
      console.log('[DashboardApp] 微前端环境，添加micro-frontend样式类');
    }

    console.log('[DashboardApp] Container cleared, mounting Vue app...');

    try {
      app.mount(container);
      console.log('[DashboardApp] ✅ Vue app mounted successfully!');

      // 验证挂载结果
      setTimeout(() => {
        console.log('[DashboardApp] Post-mount verification:');
        console.log('  - Container innerHTML length:', container.innerHTML.length);
        console.log('  - Container children count:', container.children.length);
        console.log('  - Router current route:', router.currentRoute.value.path);
      }, 100);
    } catch (error) {
      console.error('[DashboardApp] ❌ Failed to mount Vue app:', error);
      throw error;
    }
  } else {
    console.error('[DashboardApp] ❌ No valid container found for mounting');
    throw new Error('No valid container found');
  }

  // 返回应用实例和卸载函数
  return {
    app,
    unmount: async () => {
      console.log('[DashboardApp] unmount called');
      if (app) {
        app.unmount();
        app = null;
      }
    },
  };
}

// 智能检测运行环境
function detectRunningMode() {
  // 检查是否在iframe中（通常表示微前端环境）
  const inIframe = window.self !== window.top;

  // 检查是否存在qiankun标识 - 只基于qiankun标志判断
  const hasQiankunFlag = !!window.__POWERED_BY_QIANKUN__;

  console.log('[DashboardApp] Environment detection:', {
    inIframe,
    hasQiankunFlag,
    pathname: window.location.pathname,
  });

  return hasQiankunFlag;
}

// 使用vite-plugin-qiankun的方式
renderWithQiankun({
  mount(props) {
    console.log('[DashboardApp] qiankun mount called with props:', props);
    // 确保在qiankun环境中设置正确的路由基础路径
    const qiankunProps = {
      ...props,
      routerBase: '/dashboard',
    };
    createMicroApp(qiankunProps);
  },
  bootstrap() {
    console.log('[DashboardApp] qiankun bootstrap called');
  },
  unmount() {
    console.log('[DashboardApp] qiankun unmount called');
    if (app) {
      app.unmount();
      app = null;
    }
  },
  update() {
    console.log('[DashboardApp] qiankun update called');
  },
});

// 根据环境决定是否自动启动
const isMicroFrontend = detectRunningMode();

if (!isMicroFrontend) {
  console.log('[DashboardApp] Running in standalone mode');
  createMicroApp({
    routerBase: '/',
    container: document.body,
    getGlobalState: () => ({}),
    setGlobalState: () => {},
    messageService: {
      broadcast: () => {},
      subscribe: () => {},
      unsubscribe: () => {},
    },
  });
} else {
  console.log('[DashboardApp] Running in micro-frontend mode - waiting for qiankun to call mount()');
}
